package org.iogame.util;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;

/**
 * @author lc
 * @since 2022/10/1
 */
public class JsonUtil {
    /**
     * 转换为json
     *
     * @since 2022/10/1
     */
    public static String toJson(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 转换为obj
     *
     * @since 2022/10/1
     */
    public static void toObj(String json, Object cls) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        HashMap map = mapper.readValue(json, HashMap.class);
        BeanUtil.copyProperties(map, cls, false);
    }
}
